package com.wswy.wzcx.ui.main.community.add

import android.Manifest
import android.app.Activity
import android.arch.lifecycle.Observer
import android.content.Context
import android.content.Intent
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.StateListDrawable
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.support.v7.widget.Toolbar
import android.text.InputFilter
import android.text.SpannableString
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.blankj.utilcode.util.SizeUtils
import com.che.libcommon.api.BaseResult
import com.che.libcommon.api.ProgressDialogObserver
import com.che.libcommon.utils.RxBus
import com.che.libcommon.utils.ToastUtils
import com.facebook.common.util.UriUtil
import com.facebook.drawee.view.SimpleDraweeView
import com.stfalcon.frescoimageviewer.ImageViewer
import com.tbruyelle.rxpermissions2.RxPermissions
import com.wswy.wzcx.R
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.model.topic.TopicModel
import com.wswy.wzcx.model.topic.TopicTagType
import com.wswy.wzcx.module.InternalMsgCode
import com.wswy.wzcx.module.base.CBaseActivity
import com.wswy.wzcx.module.base.Func1
import com.wswy.wzcx.module.handler.TakePhotoHandler
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.dialog.ChoosePhotoBottomDialog
import com.wswy.wzcx.utils.ImageUtils
import com.wswy.wzcx.utils.RxUtils
import com.wswy.wzcx.utils.loader.FrescoEngine
import com.wswy.wzcx.widget.ChooseBottomDialog
import com.wswy.wzcx.widget.drawable.AddDrawable
import com.wswy.wzcx.widget.drawable.BaseDrawable
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import io.reactivex.Single
import kotlinx.android.synthetic.main.activity_add_topic.*
import kotlinx.android.synthetic.main.layout_app_title.*
import java.io.File

class AddTopicActivity : CBaseActivity(){


    companion object {

        private const val TAG = "AddTopicActivity"

        private const val REQUEST_CODE_CHOOSE = 23;
        private const val REQ_CHOOSE_TAG_TYPE = 25

    }

    private var currFiles : MutableList<File> = arrayListOf()

    private lateinit var addTopicViewModel: AddTopicViewModel

    private var noLoginHandler :Func1 =null

    private var selectedTag : TopicTagType ? = null

    private val takePhotoHandler = TakePhotoHandler()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_topic)
        setAppTitle("发表吐槽")

        addTopicViewModel = provideViewModel(AddTopicViewModel::class.java)
        addTopicViewModel.onCreate()
        addTopicViewModel.loadTags()


        StateListDrawable().apply {
            addState(intArrayOf(android.R.attr.state_pressed),AddDrawable(applicationContext,Color.parseColor("#f0f0f0")))
            addState(intArrayOf(0), AddDrawable(applicationContext,ContextCompat.getColor(applicationContext,R.color.dark_bg_color)))

        }.run {
            img_add.hierarchy?.setPlaceholderImage(this)
        }


        et_topic_content.filters = arrayOf(InputFilter.LengthFilter(1000))

        img_add.setOnClickListener {


            showChooseDialog()

        }

        v_choose_type.setOnClickListener {
            //showTypes()


            startActivityForResult(Intent(this,ChooseTopicTypeActivity::class.java),REQ_CHOOSE_TAG_TYPE)

        }

        tv_submit.setOnClickListener {
            clickSubmit()
        }

        addTopicViewModel.getUserLiveData().observe(this, Observer {

            it?.run {
                noLoginHandler?.invoke()
            }

        })

    }

    private fun clickSubmit(){
        if (TextUtils.isEmpty(et_topic_content.text?.toString()) && currFiles.isEmpty()){
            ToastUtils.showText("请输入吐槽内容")
            return
        }

        if (addTopicViewModel.hasLogin()){
            submit()
        }else{

            noLoginHandler = {
                submit()
            }

            addTopicViewModel.gotoLogin(this)

        }
    }


    private fun submit(){
        val content = et_topic_content.text?.toString()

        if (TextUtils.isEmpty(content) && currFiles.isEmpty()){
            ToastUtils.showText("请输入吐槽内容")
            return
        }

        if (selectedTag == null){
            ToastUtils.showText("请选择吐槽类型")
            return
        }

        currFiles.let {
            ImageUtils.clearCache()
        }

        Single.create<List<File>> { it ->
            val ret = arrayListOf<File>()

            currFiles.map {
                //gif
                if (it.extension == "gif"){
                    it
                }else{
                    ImageUtils.compress(it.absolutePath).absoluteFile
                }
            }.run {
                ret.addAll(this)
            }
            it.onSuccess(ret)
        }.compose(RxUtils.switch2io())
                .flatMap { Api.get().createTopic(content,selectedTag?.id,it) }
                .compose(RxUtils.io2main())
        .subscribe(object : ProgressDialogObserver<TopicModel>(this){
            override fun onApiResult(t: TopicModel?) {
                if (t?.id?:0 > 0){
                    ToastUtils.showText("发表成功")

                    sendClickEvent(StatisticsId.bbs_issue_tj_done)

                    setResult(Activity.RESULT_OK,Intent().apply {
                        putExtra(Constants.EXTRA_DATA,t)
                    })

                    RxBus.getDefault().postWithCode(InternalMsgCode.CODE_TOPIC_ADD,t)

                    finish()
                }else{
                    ToastUtils.showText("吐槽发表失败")
                }

            }

            override fun onApiError(result: BaseResult<*>?) {
                toastErrorMsg(result)
            }

        })

    }



    private fun showChooseDialog(){
        ChoosePhotoBottomDialog(this).apply {

            setOnItemClickListener {
                when(it){
                    0 -> {

                        takePhotoHandler.startCamera(this@AddTopicActivity){

                            currFiles.add(it)

                            showImg(currFiles)
                            updateAdd()

                            null
                        }

                    }
                    1 -> {

                        RxPermissions(this@AddTopicActivity)
                                .request(Manifest.permission.READ_EXTERNAL_STORAGE)
                                .subscribe { g ->

                                    if (g) {
                                        startChoose()
                                    } else {
                                        ToastUtils.showText("没有权限")
                                    }
                                }

                    }
                }
            }


        }.show()
    }

    override fun onBackPressed() {
        super.onBackPressed()
        sendClickEvent(StatisticsId.bbs_issue_back)
    }


    private fun startChoose(){

        val remain = 9 - currFiles.size
        if (remain <= 0){
            return
        }

        Matisse.from(this).choose(MimeType.ofImage())
                .countable(true)
                .capture(false)
                .maxSelectable(remain)
                .imageEngine(FrescoEngine())
                .forResult(REQUEST_CODE_CHOOSE)

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)


        if (resultCode == RESULT_OK){

            when(requestCode){
                REQUEST_CODE_CHOOSE -> { //选择图片

                    Matisse.obtainPathResult(data)?.asSequence()?.map {
                        File(it)
                    }?.filter {
                        it.exists()
                    }?.toMutableList()?.run {

                        currFiles.addAll(this)
                    }

                    currFiles.run {
                        showImg(this)
                        updateAdd()
                    }


                }

                REQ_CHOOSE_TAG_TYPE -> {  //选择吐槽类型

                    data?.getParcelableExtra<TopicTagType?>(Constants.EXTRA_DATA)?.run {

                        selectedTag = this
                        tv_topic_subject.text = name
                    }

                }

                else -> {
                    takePhotoHandler.handleActivityResult(requestCode, resultCode, data)
                }

            }


        }

    }


    private fun showImg(imgs:List<File?>){
        val layout = fbl_photo_container

        for (i in 0 until layout.childCount){

            layout.getChildAt(0)?.let {
                if (it.id != R.id.img_add){
                    layout.removeViewInLayout(it)
                }
            }
        }

        var len = imgs.size

        imgs.reversed().forEach {
            LayoutInflater.from(this).inflate(R.layout.topic_add_photo,layout,false)?.run {

                val position = (len--) -1

                ImageUtils.showImage(findViewById<SimpleDraweeView>(R.id.img_user_pic),it)

                findViewById<View>(R.id.img_delete)?.setOnClickListener(::clickDelete)

                setTag(R.id.item_position,position)
                setTag(R.id.item_data,imgs)
                setOnClickListener(::clickPhoto)

                layout.addView(this,0)
            }
        }


    }

    private fun updateAdd(){
        if (currFiles.size  >= 9){
            img_add.visibility = View.GONE
        }else{
            img_add.visibility = View.VISIBLE
        }
    }

    private fun clickPhoto(view: View){
        val pos = (view.getTag(R.id.item_position) as? Int)?:0

        (view.getTag(R.id.item_data) as? List<File>)?.map { UriUtil.getUriForFile(it) }?.run {
            ImageViewer.Builder(this@AddTopicActivity,this)
                    .setStartPosition(pos)
                    .show()
        }

    }

    private fun clickDelete(view: View){

        (view.parent as? View)?.run {
            val idx = fbl_photo_container.indexOfChild(this)

            if (idx != -1){
                fbl_photo_container.removeViewAt(idx)
                currFiles.removeAt(idx)

                updateAdd()
            }

        }

    }


}